package com.javaprint.order.printer;


import com.javaprint.order.vo.OrderPrint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.awt.*;
import java.awt.print.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/*
 *打印提货签收清单
 * @author LiQiuLin
 * @date 2020/3/19
 */
public class MyOrderTotalPrint implements Printable {
    private static final Logger logger = LoggerFactory.getLogger(MyOrderTotalPrint.class);

    //列表字段名称
    private List<String> listFieldTitles = new ArrayList<>(Arrays.asList("序号", "订单编码", "收货人", "发货人", "启运地"));
    private List<String> listFieldKeys = new ArrayList<>(Arrays.asList("no", "orderCode", "consigneeName", "shipperName", "startAddress"));
    private List<OrderPrint> dataList;
    private Integer totalCount;
    //每个条项的长度
    private float filedW = 120;
    //list里面字段的默认长度
    private float commonListItemW = 80;
    //序号
    private int dataNo = 0;
    //标题
    private String title = "签收清单";

    private List<Float> listFieldWidths = new ArrayList<>(Arrays.asList(commonListItemW,commonListItemW,commonListItemW,commonListItemW,commonListItemW,commonListItemW));
    public Integer getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public MyOrderTotalPrint() {
    }

    public MyOrderTotalPrint(List<OrderPrint> dataList) {
        this.dataList = dataList;
        logger.info("进入订单签收清单");
    }

    @Override
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
        System.out.println("pageIndex为:" + pageIndex);
        //获取数据
        Graphics2D g2 = (Graphics2D) graphics;
        g2.setColor(Color.black);
        if (pageIndex > totalCount) {
            return NO_SUCH_PAGE;
        } else {
            //打印，设置字体
            Font defaultFont = new Font("宋体",Font.BOLD,12);
            g2.setFont(defaultFont);
            //转换坐标，确定打印边界
            g2.translate(pageFormat.getImageableX(),pageFormat.getImageableY());
            //设置打印x，y
            double x = pageFormat.getImageableX();
            double y = pageFormat.getImageableX();

            //获取字体的高度
            float height = defaultFont.getSize2D();

            //表格线微调值
            float lineFineTuning = 5;
            //设置列表项标题
            float line = 5;
            //画上横线
            g2.drawLine((int) (x - lineFineTuning), (int) (y + line - height + lineFineTuning), (int) (x + getlistFieldWidthTotal()), (int) (y + line - height + lineFineTuning));
            //画左竖线
            g2.drawLine((int) (x - lineFineTuning), (int) (y + line - height + lineFineTuning), (int) (x - lineFineTuning), (int) (y + line + lineFineTuning));
            for (int i = 0; i < listFieldTitles.size(); i++) {
                float offsetNum = 0;
                for (int j = 0; j < i; j++) {
                    offsetNum += listFieldWidths.get(j);
                }
                g2.drawString(listFieldTitles.get(i).toString(), (float) x + offsetNum, (float) y + line);
                //画竖线
                int temX = (int) (x + getlistFieldWidthTotal(i) - lineFineTuning);
                if (i == listFieldTitles.size() - 1) {
                    temX = temX + (int) lineFineTuning;
                }
                g2.drawLine(temX, (int) (y + line - height + lineFineTuning), temX, (int) (y + line + height));
            }
            //画下横线
            g2.drawLine((int) (x - lineFineTuning), (int) (y + line + lineFineTuning), (int) (x + getlistFieldWidthTotal()), (int) (y + line + lineFineTuning));

            //设置列表项数据
            line += height;
            if (dataList != null && dataList.size() > 0) {
                for (int i = 0; i < dataList.size(); i++) {
                    dataNo++;
                    for (int k = 0; k < listFieldKeys.size(); k++) {
                        float offsetNum = 0;
                        for (int j = 0; j < k; j++) {
                            offsetNum += listFieldWidths.get(j);
                        }
                        String filedValue = "";
                        //如果是序号列
                        if (k == 0) {
                            filedValue = String.valueOf(dataNo);
                        } else {
                            filedValue = getValueByKey(dataList.get(i), listFieldKeys.get(k)).toString();
                        }
                        g2.drawString(filedValue, (float) x + offsetNum, (float) y + line);
                        //画竖线
                        int temX = (int) (x + getlistFieldWidthTotal(k) - lineFineTuning);
                        if (k == listFieldTitles.size() - 1) {
                            temX = temX + (int) lineFineTuning;
                        }
                        g2.drawLine(temX, (int) (y + line - height + lineFineTuning), temX, (int) (y + line + lineFineTuning));
                        //画下横线
                        g2.drawLine((int) (x - lineFineTuning), (int) (y + line + lineFineTuning), (int) (x + getlistFieldWidthTotal()), (int) (y + line + lineFineTuning));
                    }
                    //画左竖线
                    g2.drawLine((int) (x - lineFineTuning), (int) (y + line - height + lineFineTuning), (int) (x - lineFineTuning), (int) (y + line + lineFineTuning));
                    line += height;
                }
            }
        }



        return PAGE_EXISTS;
    }

    //获取列表字段总宽度
    private float getlistFieldWidthTotal() {
        float widthTotal = 0;
        for (int i = 0; i < listFieldWidths.size(); i++) {
            widthTotal += listFieldWidths.get(i);
        }
        return widthTotal;
    }

    //获取截止到某个字段索引的字段总宽度 index从0开始
    private float getlistFieldWidthTotal(int index) {
        float widthTotal = 0;
        for (int i = 0; i <= index; i++) {
            widthTotal += listFieldWidths.get(i);
        }
        return widthTotal;
    }
    /**
     * 获取对象属性值
     *
     * @param obj 对象
     * @param key key值
     * @return
     */
    public static Object getValueByKey(Object obj, String key) {
        // 得到类对象
        Class userCla = (Class) obj.getClass();
        /* 得到类中的所有属性集合 */
        Field[] fs = userCla.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            f.setAccessible(true); // 设置些属性是可以访问的
            try {
                if (f.getName().endsWith(key)) {
                    return f.get(obj);
                }
            } catch (IllegalArgumentException e) {
                logger.error("非法参数，反射获取属性值异常",e);
            } catch (IllegalAccessException e) {
                logger.error("反射不可入",e);
            }
        }
        // 没有查到时返回空字符串
        return "";
    }

    public void doPrint(Printable printTable){
        logger.info("打印打票的一些配置");
        try {
            //定义book，传递对象
            Book book = new Book();
            //定义规则，设置方向
            PageFormat pageFormat = new PageFormat();
            pageFormat.setOrientation(PageFormat.PORTRAIT);//从左到右，从上到下
            //定义纸张大小
            Paper paper = new Paper();
            paper.setSize(595,843);
            //设置打印区域
            paper.setImageableArea(5,10,580,820);
            pageFormat.setPaper(paper);
            book.append(printTable,pageFormat,this.totalCount);
            //获取打印服务
            PrinterJob printerJob = PrinterJob.getPrinterJob();
            printerJob.setPageable(book);//设置打印类
            printerJob.print();
        } catch (PrinterException e) {
            logger.error("打印异常");
        }


    }
}
